package com.example.hrandroidapp;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import lib.jason.requestresponsetask.HTTPUtils;
import lib.jason.requestresponsetask.JSONHTTPPoster;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hrandroidapp.adapter.CustomSpinnerAdapter;
import com.example.hrandroidapp.common.Constant;
import com.example.hrandroidapp.common.DateUtils;
import com.example.hrandroidapp.common.HRLog;
import com.example.hrandroidapp.components.MMEditText;
import com.example.hrandroidapp.domain.TaskType;
import com.example.hrandroidapp.fragment.DatePickerFragment;
import com.example.hrandroidapp.fragment.TimePickerFragment;
import com.example.hrandroidapp.fragment.TimePickerFragment.TimePickerValueCallBack;
import com.example.hrandroidapp.preferences.CurrentServerPreference;
import com.example.hrandroidapp.preferences.UserPreference;
import com.gc.materialdesign.widgets.Dialog;

public class CreateOverTimeActivity extends ActionBarActivity implements DatePickerFragment.DatePickerValueCallBack,
						TimePickerValueCallBack {

	private TextView tvOTDate, tvStartTime; // , tvHour;
	private MMEditText etReason;
	private Date otDate;
	private int timeStartEnd = 0;  // 1 for start, 2 for end
	private String url=null;
	
	private ArrayList<TaskType> lstTaskType;
	private Long selectedTaskType;
	private CustomSpinnerAdapter adapter;
	private Spinner spinner, hrSpinner;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_overtime);
		
		loadViews();

		tvOTDate.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDatePickerDialog(v);
			}
		});
		
		tvStartTime.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showTimePickerDialog(v);
				timeStartEnd = 1;
			}
		});
		
//		tvHour.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				showTimePickerDialog(v);
//				timeStartEnd = 2;
//			}
//		});

		loadOTType();

	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.new_leave_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(android.view.MenuItem item) {
		int id = item.getItemId();
		
		if(id == R.id.action_send) {
			overtimeApply(); 
		}else if(id == android.R.id.home) {
			onBackPressed();
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	private void loadViews() {
		spinner = (Spinner) findViewById(R.id.ot_type_spinner);
		hrSpinner = (Spinner) findViewById(R.id.sp_hr);
		tvOTDate = (TextView) findViewById(R.id.tv_ot_start_date);
		tvStartTime = (TextView) findViewById(R.id.tv_ot_start_time);
//		tvHour = (TextView) findViewById(R.id.tv_end_time);
		etReason = (MMEditText) findViewById(R.id.et_reason);
	}
	
	public void showDatePickerDialog(View v) {
	    DialogFragment newFragment = new DatePickerFragment(this);
	    newFragment.show(getSupportFragmentManager(), "datePicker");
	}
	
	private void overtimeApply() {

		url = getResources().getString(R.string.overtime_apply_url);
		String completeUrl = "http://" + CurrentServerPreference.getCurrentServer(this).getSvrIP() + ":" + Constant.PORT + url;
		
		JSONObject jsonObj = new JSONObject();
		try {
			int pos = hrSpinner.getSelectedItemPosition();
			int hr = 0;
			if(pos%2 == 0) {
				String tmpVal = hrSpinner.getSelectedItem().toString();
				hr = Integer.parseInt(tmpVal.replace(".00", ""));
				hr = hr * 60;
			}else {
				double tmpHr = Double.parseDouble(hrSpinner.getSelectedItem().toString().trim());
				hr = (int) tmpHr;
				hr = (hr * 60) + 30;
			}
			
			TaskType spTaskType = (TaskType) spinner.getItemAtPosition(spinner.getSelectedItemPosition());
			
			jsonObj.put("loginId", UserPreference.getLoginId(this));
			jsonObj.put("userID", UserPreference.getUserId(this));
			jsonObj.put("otDate", DateUtils.convert(otDate, "yyyyMMddHHmmss"));
			jsonObj.put("otType", spTaskType.getId());
			jsonObj.put("minutes", hr);
			jsonObj.put("task", etReason.getText().toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}

		String paramString = jsonObj.toString();	
		
		HRLog.postLogInfo("leave apply url complete: " + completeUrl, " at CreateLeaveActivity.leaveApply"); 
		new HTTPUtils(this, JSONHTTPPoster.MEDIA_JSON_TYPE, completeUrl, paramString, 
				new HTTPUtils.SimpleRequestResponseTaskInterface() {

			@Override
			public void handleResponse(String responseStr, int status) throws Exception {
				HRLog.postLogDebug("response status: " + status, " at CreateLeaveActivity.leaveApply");
				if(status == 200) {
					Toast.makeText(getBaseContext(),"Leave send successfully...",Toast.LENGTH_LONG).show();
					finish(); 
				}else {
					Toast.makeText(getBaseContext(),"Leave send Fail!!",Toast.LENGTH_LONG).show();
				}
			}
			
		}).execute();
	}
	
	private void loadOTType() {

		url = getResources().getString(R.string.overtime_type_url);
		String completeUrl = "http://" + CurrentServerPreference.getCurrentServer(this).getSvrIP() + ":" + Constant.PORT + url;
		
		new HTTPUtils(this, JSONHTTPPoster.MEDIA_FORM_URLENCODED, completeUrl, "", 
				new HTTPUtils.SimpleRequestResponseTaskInterface() {

			@Override
			public void handleResponse(String responseStr, int status) throws Exception {
				
				ObjectMapper mapper = new ObjectMapper();
				
				lstTaskType = mapper.readValue(responseStr, TypeFactory.collectionType(List.class, TaskType.class));
				selectedTaskType = lstTaskType.get(0).getId();
				adapter = new CustomSpinnerAdapter(CreateOverTimeActivity.this, R.layout.leave_type_spinner, lstTaskType, true);
				spinner.setAdapter(adapter);

			}
			
		}).execute();
		
	}

	public void showTimePickerDialog(View v) {
	    DialogFragment newFragment = new TimePickerFragment(this);
	    newFragment.show(getSupportFragmentManager(), "timePicker");
	}

	@Override
	public void returnDatePickerValue(int year, int month, int day) {
		Integer value = (year * 10000) + (++month * 100) + day;
		
		Date pickDate = DateUtils.convert(value, DateUtils.DATE_YYYYMMDD_FORMAT);
		Date todayDate = new Date();

		todayDate = DateUtils.setHourMinSec(todayDate, 0, 0, 0, 0);
		
		if(pickDate.before(todayDate)) {
			Dialog dialog = new Dialog(CreateOverTimeActivity.this, "Invalid Request Date", 
					"Overtime request date should be after today date.", "OK", "", true, false);
			
			dialog.setOnCancelButtonClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
				}
			});
			dialog.show();
		}else {
			tvOTDate.setText(DateUtils.getDateInString(year, month, day, DateUtils.DATE_YYYYMMDD_FORMAT));
			otDate = DateUtils.convert(value, DateUtils.DATE_YYYYMMDD_FORMAT); 
		}
	}

	@Override
	public void returnTimePickerValue(int hourOfDay, int minute) {
		switch(timeStartEnd) {
		case 1:
			tvStartTime.setText(DateUtils.getHourMinInString(hourOfDay, minute));
			otDate = DateUtils.setHourMinSec(otDate, hourOfDay, minute, 0, 0);
			break;
//		case 2:
//			tvHour.setText(DateUtils.getHourMinInString(hourOfDay, minute));
//			break;
		}
		timeStartEnd = 0;
	}
	
}
